let layerIndex;
let $;
var toast;
var table;

/**
 * 获得搜索条件
 * @returns {{}}
 */
function getSearchCondition() {
    //获取数据
    let formData = {}
    $("#queryForm").find("input,select").each(function () {
        let name = $(this).attr("name");
        let value = $(this).val();

        if (name && value) {
            formData[name] = value;
        }
    });

    return formData;
}

/**
 * 获取当前登录学生的ID
 * @returns {number}
 */
async function getCurrentStudentId() {
    var userId = JSON.parse(sessionStorage.getItem('userInfo'))?.userId;
    if (!userId) {
        console.error("用户未登录或sessionStorage无userInfo");
        window.location.href = "/login";
        throw new Error("用户未登录");
    }

    try {
        const res = await $.ajax({
            url: "/api/admin/student/getByUserId",
            method: "GET",
            data: { userId: userId },
        });

        // 根据你的返回数据结构调整
        if (res.code === 0) {
            // 直接返回教师ID，因为API返回的是Teacher对象
            console.log("获取到的信息:", res.data);
            return res.data; // 修改这里
        } else {
            console.error("获取教师ID失败:", res.msg);
            return userId;
        }
    } catch (error) {
        console.error("AJAX请求失败:", error);
        return userId;
    }
}

/**
 * 初始化成绩表格
 */
function initScoreTable(studentId) {
    console.log("学生id：",studentId)
    if (!studentId) {
        layer.msg('请先登录', {icon: 2});
        return;
    }

    table.render({
        elem: "#tbStudent",
        url: "/api/admin/student/getbypage",
        method: "POST",
        contentType: "application/json",
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        where: {
            data: {
                student: {
                    stuId: studentId
                }
            }
        },
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'courseId', fixed: 'left', width: 80, title: 'ID', sort: true},
            {field: 'courseName', title: '课程名称'},
            {field: 'courseCode', title: '课程代码', width: 150},
            {field: 'teacherName', title: '授课教师', width: 120,templet: function(d){
                    return d.teacher ? d.teacher.teacherName : '无';
                }},
            {field: 'score', title: '成绩', width: 100, sort: true},

            {fixed: 'right', title: "操作", width: 134, minWidth: 125, templet: "#editTemplate"}
        ]],
        done: function (rs) {
            console.log(rs)
        }
    });
}

layui.use(['form', 'table', 'layer'], function () {
    $ = layui.$;
    toast = layui.layer;
    const form = layui.form;
    table = layui.table;

    // 初始化成绩表格
    (async () => {
        try {
            const studentId = await getCurrentStudentId();
            console.log("当前教师ID:", studentId);
            initScoreTable(studentId);
        } catch (error) {
            console.error("初始化失败:", error);
            layer.msg('初始化失败: ' + error.message, {icon: 2});
        }
    })();

    // 确保表单渲染
    form.render();

    // 表单提交处理
    form.on('submit(stud-dlg)', function (data) {
        event.preventDefault();
        if(this.isSumitting) return false;
        this.isSumitting = true;
        commitStuDlg()
            .catch(error => {
                console.error("提交错误", error);
            })
            .finally(() => {
                this.isSumitting = false;
            });
        return false;
    });
});

/**
 * 搜索功能
 */
function search() {
    const studentId = getCurrentStudentId();
    if (!studentId) {
        layer.msg('请先登录', {icon: 2});
        return;
    }

    let condition = getSearchCondition();
    condition.studentId = studentId; // 确保只查询当前学生的成绩

    table.reload("tbStudent", {
        where: {data: condition},
        page: {curr: 1}
    });
}

/**
 * 显示学生对话框
 */
function showStudentDlg() {
    layer.msg('此功能需要后端支持', {icon: 6});
}

/**
 * 删除确认
 */
function deleteConfrim() {
    layer.msg('此功能需要后端支持', {icon: 6});
}